#!/usr/bin/env python3
# vim:fileencoding=utf-8

import os
import sys
import argparse
import subprocess
import locale
locale.setlocale(locale.LC_ALL, '')

from pygments import highlight
import pygments.util
from pygments.lexers import get_lexer_by_name
from pygments.formatters import TerminalFormatter, Terminal256Formatter
from pygments.lexers import guess_lexer, guess_lexer_for_filename

def main(fname, lang):
  if fname == '-':
    code = sys.stdin.read()
  else:
    code = open(fname).read()
  if lang:
    lexer = get_lexer_by_name(lang)
  else:
    try:
      lexer = guess_lexer_for_filename(fname, code)
    except pygments.util.ClassNotFound:
      lexer = guess_lexer(code)
    except TypeError:
      # unordered LexerMeta(); should be an issue in pygments
      if os.path.splitext(fname)[1].lower() in ('.html', '.htm'):
        # if guessed, it would be xml instead.
        lexer = get_lexer_by_name('html')
      else:
        lexer = get_lexer_by_name('text')

  if sys.stdout.isatty():
    p = subprocess.Popen(['less', '-RFXM'], stdin=subprocess.PIPE,
                         universal_newlines=True)
    output = p.stdin
  else:
    p = None
    output = sys.stdout
  # formatter = Terminal256Formatter if os.environ.get('TERM', '').find('256') != -1 else TerminalFormatter
  formatter = TerminalFormatter
  try:
    print(highlight(code, lexer, formatter()), file=output, end='')
  except IOError: # SIGPIPE
    pass
  if p:
    output.close()
    p.wait()

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='用 less 显示高亮的代码')
  parser.add_argument('files', metavar='FILE', nargs='*',
                     help='要高亮的文件')
  parser.add_argument('-l', '--lang', dest='lang', default=None,
                     help='语法类型')

  args = parser.parse_args()
  if args.files:
    for l in args.files:
      main(l, args.lang)
  else:
    main('-', args.lang)
